package cn.felord.function;

import cn.felord.function.routes.UserController;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.function.RequestPredicates;
import org.springframework.web.servlet.function.RouterFunction;
import org.springframework.web.servlet.function.RouterFunctions;
import org.springframework.web.servlet.function.ServerResponse;

/**
 * The type Endpoint configuration.
 */
@Configuration
@Slf4j
public class EndpointConfiguration {


    /**
     * 统一前缀
     *
     * @param userController the user controller
     * @return the router function
     */
    @Bean
    RouterFunction<ServerResponse> userEndpoints(UserController userController) {
        return RouterFunctions.route()
                .path("/v2/user", builder -> builder
                        //  /get/{username} -> /v2/user//get/{username}
                        .add(userController.getUserByName()
                                //  /del/{username} -> /v2/user//del/{username}
                                .and(userController.delUser()
                                        // /save -> /v2/user/save
                                        .and(userController.saveUser()
                                                // /update -> /v2/user/update
                                                .and(userController.updateUser())))))
                .build();
    }


    /**
     * 统一处理.
     *
     * @param userController the user controller
     * @return the router function
     */
    @Bean
    RouterFunction<ServerResponse> nestEndpoints(UserController userController) {
        return RouterFunctions.route().nest(RequestPredicates.path("/v1/user"),
                builder -> builder
                        .add(userController.getUserByName())
                        .add(userController.delUser())
                        .add(userController.saveUser())
                        .add(userController.updateUser()))
                // 对上述路由进行统一的异常处理
                .onError(RuntimeException.class,
                        (throwable, serverRequest) -> ServerResponse
                                .status(HttpStatus.BAD_REQUEST)
                                .body("bad req"))
                .build();
    }


}
